package com.biodiv.community.manager.mq;

import com.alibaba.fastjson2.JSONObject;
import com.biodiv.community.enums.TopicEnum;
import com.biodiv.community.event.BaseEvent;
import lombok.AllArgsConstructor;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.biodiv.community.constant.CommonConstant.TRACE_ID;

/**
 * @author tianquan
 */
@Service
@AllArgsConstructor
public class RedisPublisher {

    private final StringRedisTemplate stringRedisTemplate;

    public <T extends BaseEvent> void publish(TopicEnum topic, T message) {
        if (message == null){
            throw new NullPointerException("message is null");
        }
        String channel = topic.getType();
        // 设置消息id
        message.setMessageId(String.valueOf(System.currentTimeMillis()));
        // 设置traceId
        message.setTraceId(MDC.get(TRACE_ID));
        // 转为json
        String jsonMessage = JSONObject.toJSONString(message);
        // 发送消息
        stringRedisTemplate.convertAndSend(channel, jsonMessage);
    }

}